package com.chj.comp.service.demo1.listener.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.chj.comp.common.core.constant.CommonConstant;
import com.chj.comp.common.core.feign.RemoteMqadminService;
import com.chj.comp.common.core.util.Result;
import com.chj.comp.common.rabbitmq.constant.MsgStatusEnum;
import com.chj.comp.common.rabbitmq.message.MessageEntity;
import com.chj.comp.common.rabbitmq.queue.MqSimpleQueue;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Component
// queuesToDeclare队列不存在自动创建
@RabbitListener(queuesToDeclare = @Queue(MqSimpleQueue.QUEUE_NAME), ackMode = "MANUAL")
public class MqSimpleListener {

    @Resource
    private RemoteMqadminService remoteMqadminService;

    // isDefault-不管生产者生产哪种类型的消息，消费者设置默认处理
    @RabbitHandler(isDefault = true)
    public void handleMessage(Message message,
                               Channel channel,
                               @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        MessageProperties messageProperties = message.getMessageProperties();
        // STEP5：确认收到消息(确认后，生产者不在重复发送)
        // false 当前消费者确认收到，true 所有消费者确认收到
        try {
            channel.basicAck(deliveryTag, false);
            remoteMqadminService.updateMqMessageStatus(messageProperties.getMessageId(), MsgStatusEnum.STATUS_2.getStatus());
        } catch (IOException e) {
            log.error("消息手动确认失败：{}", messageProperties.getMessageId());
        }

        // STEP6：判断消息是否为重复消费
        Result<Integer> result = remoteMqadminService.judgeMqMessageStatus(messageProperties.getMessageId());
        if(result.getCode() == CommonConstant.SUCCESS && result.getData() > 0){
            return;
        }

        // STEP7：消费消息
        MessageEntity messageEntity = JSON.parseObject(message.getBody(), MessageEntity.class);
        log.info("消费消息（简单队列）-->{}:{}", messageProperties.getMessageId(), messageEntity.getName());

        // STEP8：消息消费完成后，将消息状态改为已消费
        remoteMqadminService.updateMqMessageStatus(messageProperties.getMessageId(), MsgStatusEnum.STATUS_3.getStatus());
    }
}
